/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * TrainingBook
 * Copyright (C) Arnaud Duval 2010 <arnaud.duval@gmail.com>
 * 
 * Projects is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Projects is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <tcx-import-dialog.hpp>
#include <libxml++/libxml++.h>
#include <ActivityHeader.hpp>
#include <ActivityHistory.hpp>


///@brief Default constructor
///@param title Title of the dialog
///@param parent Pointer to the parent window
///@param tcxFilePath Path to the TCX file to import
TcxImportDialog::TcxImportDialog(std::string title, 
                                       Gtk::Window *parent,
                                       std::string tcxFilePath)
: Gtk::Dialog(title, *parent)
{
    ///@brief Set the border width of the window
    set_border_width(0);
    ///@brief set the labels text
    //FillLabels();

    importHeaderList.clear();
    bool result = ReadHeaderFromTcx(tcxFilePath);

    get_vbox()->pack_start(activityTV, Gtk::PACK_SHRINK);
    
    ///@brief Addition of buttons for cancel or validation
    add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
    add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
    
    show_all();
}

///@brief Called at validation
///@param response_id Response ID
void TcxImportDialog::on_response(int response_id)
{

}

///@brief Routine to read a TCX file
///@param tcxFilePath Path to the TCX file to read
bool TcxImportDialog::ReadHeaderFromTcx(std::string tcxFilePath)
{
    filePath = tcxFilePath;
    try
    {
        xmlpp::DomParser parser;
        parser.set_substitute_entities();
        parser.parse_file(tcxFilePath);
        if(parser)
        {
            // Walk the tree
            const xmlpp::Node* rootNode = parser.get_document()->get_root_node();
            Glib::ustring nodename = rootNode->get_name();
            if(nodename == "TrainingCenterDatabase")    //root node is a Garmin Training Center Database
            {
                xmlpp::Node::NodeList rootChildren = rootNode->get_children();
                for(xmlpp::Node::NodeList::iterator iterRootChildren = rootChildren.begin();
                    iterRootChildren != rootChildren.end();
                    ++iterRootChildren)
                {
                    xmlpp::Node* rootChildNode = dynamic_cast<const xmlpp::Node*>(*iterRootChildren);
                    if(rootChildNode->get_name() == "Activities")
                    {
                        xmlpp::Node::NodeList activitiesChildren = rootChildNode->get_children();
                        for(xmlpp::Node::NodeList::iterator iterActivitiesChildren = activitiesChildren.begin();
                            iterActivitiesChildren != activitiesChildren.end();
                            ++iterActivitiesChildren)
                        {
                            xmlpp::Node* activityNode = dynamic_cast<const xmlpp::Node*>(*iterActivitiesChildren);
                            if(activityNode->get_name() == "Activity")
                            {
                                ActivityHeader activityHeader;
                                activityHeader.ReadFromTcxFile(activityNode);
                                Gtk::TreeModel::iterator iter = activityTV.refImportActivityListTreeModel->append();
                                Gtk::TreeModel::Row row = *iter;
                                row[activityTV.activityColumns.m_col_activitytype] = activityHeader.GetActivityType();
                                row[activityTV.activityColumns.m_col_activityId] = activityHeader.GetId();
                                row[activityTV.activityColumns.m_col_date] = activityHeader.GetDateTime().AsString("dd/mm/yyyy");
                                row[activityTV.activityColumns.m_col_time] = activityHeader.GetDateTime().AsString("hh:nn");
                                row[activityTV.activityColumns.m_col_duration] = activityHeader.GetDuration().AsText();
                                row[activityTV.activityColumns.m_col_distance] = activityHeader.GetDistance();
                                importHeaderList.push_back(activityHeader);
                            }
                        }
                    }
                }
            }
            
        }
    }
    catch(const std::exception& ex)
    {
        std::cerr << "Exception caught: " << ex.what() << std::endl;
        return false;
    }

    return true;
}

///@brief Return a list of imported activities
std::list<Activity> TcxImportDialog::DoTcxImport()
{
    std::list<Activity> res;
    if(importHeaderList.empty())
        return res;
        
    for(std::list<ActivityHeader>::iterator iter = importHeaderList.begin() ; 
        iter != importHeaderList.end();
        ++iter)
    {
        try
        {
            xmlpp::DomParser parser;
            parser.set_substitute_entities();
            parser.parse_file(filePath);
            if(parser)
            {
                // Walk the tree
                const xmlpp::Node* rootNode = parser.get_document()->get_root_node();
                Glib::ustring nodename = rootNode->get_name();
                if(nodename == "TrainingCenterDatabase")    //root node is a Garmin Training Center Database
                {
                    xmlpp::Node::NodeList rootChildren = rootNode->get_children();
                    for(xmlpp::Node::NodeList::iterator iterRootChildren = rootChildren.begin();
                        iterRootChildren != rootChildren.end();
                        ++iterRootChildren)
                    {
                        xmlpp::Node* rootChildNode = dynamic_cast<const xmlpp::Node*>(*iterRootChildren);
                        if(rootChildNode->get_name() == "Activities")
                        {
                            xmlpp::Node::NodeList activitiesChildren = rootChildNode->get_children();
                            for(xmlpp::Node::NodeList::iterator iterActivitiesChildren = activitiesChildren.begin();
                                iterActivitiesChildren != activitiesChildren.end();
                                ++iterActivitiesChildren)
                            {
                                xmlpp::Node* activityNode = dynamic_cast<const xmlpp::Node*>(*iterActivitiesChildren);
                                if(activityNode->get_name() == "Activity")
                                {
                                    ActivityHistory activityHistory;
                                    activityHistory.ReadFromTcxFile(activityNode, iter->GetId());
                                    Activity newActivity;
                                    newActivity.SetHeader(*iter);
                                    newActivity.SetHistory(activityHistory);
                                    res.push_back(newActivity);
                                }
                            }
                        }
                    }
                }
            }
        }
        catch(const std::exception& ex)
        {
            std::cerr << "Exception caught: " << ex.what() << std::endl;
        }
    }   
}




